<!DOCTYPE html>
<html class="x-admin-sm">
<head>
    <meta charset="UTF-8">
    <title>宇成建筑</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="../statics/css/font.css">
    <link rel="stylesheet" href="../statics/plugins/layui/css/layui.css">
    <link rel="stylesheet" href="../statics/css/xadmin.css">
    <link rel="stylesheet" href="../statics/css/style.css">
    <style>
        input.price{
            height:25px !important;
        }
        .layui-table-cell {
            padding: 0px 10px;
        }
        .budget.layui-table td, .budget.layui-table th {
            padding: 7px 10px;
        }
        .budget th:first-child, .budget td:first-child{
            text-align: center;
            width: 10%;
        }
        .layui-table td, .layui-table th {
            min-width: 60px;
        }
    </style>
</head>

<body class='labelAuto'>
<div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="welcome.html">首页</a>
            <a href="javascript:;">施工管理</a>
            <a class="projectName"></a>
            <a class="areaName"></a>
            <a><cite>施工段列表</cite></a>
        </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       onclick="location.reload()" title="刷新">
        <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i>
    </a>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right;margin-right:10px"
       onclick="window.history.go(-1)" title="后退">
        <i class="iconfontBlod" style="line-height:30px">&#xe74f;</i>
    </a>
</div>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body search">
                    <form action="" class="layui-form livingList">
                        <div class="layui-item">
                            <div class="layui-inline">
                                <label for="" class="layui-form-label">搜索</label>
                                <div class="layui-input-block">
                                    <input type="text" class="layui-input" id='searchInput'>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button class="layui-btn search" type="button" id='search'>
                                    <i class="iconfont layui-icon">&#xe615;</i>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="layui-card-body tableCardBody">
                    <table class="layui-table" id="lists" lay-filter="test"></table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script src="../statics/plugins/layui/layui.js" charset="utf-8"></script>
<script src='../statics/plugins/jQuery-3.2.1/jquery-3.2.1.min.js'></script>
<script type="text/javascript" src="../statics/plugins/X-admin/xadmin.js"></script>
<script type="text/javascript" src="../statics/js/public.js?v=1129"></script>
<script type="text/javascript">
    layui.use(['layer', "table"], function () {
        var table = layui.table;
        var layer = layui.layer;
        $('.projectName').empty().html(localStorage.getItem('projectName'))
        $('.areaName').empty().html(localStorage.getItem('areaName'))
        var areaId = getQueryString('id');
        var projectId = getQueryString('projectId');
        var professionLists = [];
        $.ajax({
            url: url + "/setting/profession/selectLists",
            type: "POST",
            async: false,
            data: {
                token: getToken()
            },
            success: function (r) {
                professionLists = r.data;
            }
        });
        var column1 = [
            {field: '', title: '编号', type: 'numbers', width: '60', rowspan: 2, fixed: 'left'},
            {field: 'name', title: '楼栋/施工区', width: '120', rowspan: 2, fixed: 'left'},
            {
                field: 'area', title: '建筑面积', width: '90', rowspan: 2, fixed: 'left', templet: function (d) {
                    return Number(d.area);
                }
            },
            {field: 'budgetFormworkArea', title: '预算模板面积', width: '110', rowspan: 2, fixed: 'left', templet: function (d) {
                    return Number(d.budgetFormworkArea);
                }},
            {field: 'formworkArea', title: '施工模板面积', width: '110', rowspan: 2, fixed: 'left', templet: function (d) {
                    return Number(d.formworkArea);
                }},
            {field: '', title: '概览', colspan: 4, align: 'center'}
        ];
        var column2 = [
            {field: `budget`, title: `控制总价`, width: '120',templet(d){return numberFormat(d.budget,'currency')}},
            {field: `cost`, title: `成本`, width: '120',templet(d){return numberFormat(d.cost,'currency')}},
            {field: `budgetPrice`, title: `控制单价`, width: '80',templet(d){return d.budgetPrice=='-'?'-':numberFormat(d.budgetPrice,'currency')}},
            {field: `costPrice`, title: `成本单价`, width: '80',templet(d){
                let style = d.budgetPrice <d.costPrice?'style="color:#FF5722"':'';
                return d.costPrice=='-'?'-':`<span ${style}>${numberFormat(d.costPrice,'currency')}</span>`
            }}
        ];
        for (let i = 0; i < professionLists.length; i++) {
            column1.push({field: '', title: professionLists[i].name, colspan: 4, align: 'center'});
            column2.push({field: `b_p_${professionLists[i].id}`, title: `控制总价`, width: '120',templet(d){return numberFormat(d['b_p_'+professionLists[i].id],'currency')}});
            column2.push({field: `p_${professionLists[i].id}`, title: `成本`, width: '120',templet(d){return numberFormat(d['p_'+professionLists[i].id],'currency')}});
            column2.push({
                field: `b_pp_${professionLists[i].id}`,
                title: `控制单价`,
                width: '80',
                templet(d){return d['b_pp_'+professionLists[i].id]=='-'?'-':numberFormat(d['b_pp_'+professionLists[i].id],'currency')}
            });
            column2.push({field: `pp_${professionLists[i].id}`, title: `成本单价`, width: '80',templet(d){return d['pp_'+professionLists[i].id]=='-'?'-':numberFormat(d['pp_'+professionLists[i].id],'currency')}});
        }
        column1.push(
            {
                field: '', title: '操作', rowspan: 2, fixed: 'right', width: '220', templet: function (d) {
                    return `<button class='workSection layui-btn' lay-event="editCost" data-id=${d.id}>编辑预算</button>
                            <button class='layui-btn' lay-event="formworkArea" data-id=${d.id}>设置模板面积</button>`
                }
            }
        );
        // 异步数据加载
        var lists = table.render({
            elem: '#lists', //绑定DOM元素
            id: 'lists', //table的id
            title: '人员列表',
            height: 'full-150',
            contentType: "application/json; charset=utf-8",
            url: url + '/project/project/budgetSection', //数据接口地址
            request: {
                pageName: 'page', //页码的参数名称，默认：page
                limitName: 'length' //每页数据量的参数名，默认：limit
            },
            method: 'POST',
            parseData: function (res) {
                return {
                    "code": res.code, //解析接口状态
                    "data": res.data.data,
                    "msg": res.msg,
                    "count": res.data.count
                };
            },
            where: {
                areaId: areaId,
                search: "",
                token: getToken()
            },
            toolbar: '#toolbar',
            defaultToolbar: ['filter'],
            page: true, //开启分页
            limit: 10, //默认每页记录条数
            limits: [10, 20, 50], //每页记录条数可选数量
            cols: [
                column1,
                column2
            ],
            response: {
                statusName: 'code', //数据状态的字段名称，默认：code
                statusCode: 100000, //成功的状态码，默认：0
                msgName: 'msg', //状态信息的字段名称，默认：msg
                countName: 'count', //数据总数的字段名称，默认：count
                dataName: 'data' //数据列表的字段名称，默认：data
            },
            done:function(){
                permission();
            }
        });

        table.on('tool(test)',function(data){
            if(data.event=='editCost'){
                var id = Number(data.data.id);
                var area = Number(data.data.area);
                var budgetFormworkArea = Number(data.data.budgetFormworkArea);
                var lists = '';
                $.ajax({
                    url:url+'/project/project/budgetDetail',
                    type: "POST",
                    async: false,
                    data: {
                        sectionId:id,
                        token:getToken()
                    },
                    success:function(r){
                        if(r.code!=100000){
                            tips('成本',r);
                            return false;
                        }else{
                            lists = r.data;
                        }
                    }
                });
                html = `<table class="layui-table budget" style="width:98%;margin-left:auto;margin-right:auto;"><thead><tr><th>编号</th><th>工种</th><th>面积（平方米）</th><th>单价（元/平方米）</th><th>总价（元）</th></tr></thead><tbody>`
                for (var i= 0;i<lists.length;i++){
                    var tmp = 0;
                    if (lists[i].isFormwork === 0){
                        tmp = area;
                    }else{
                        tmp = budgetFormworkArea;
                    }
                    html+=`<tr>
                            <td>${i+1}</td>
                            <td class='professionId' data-id="${lists[i].budgetId}" data-professionid="${lists[i].id}">${lists[i].name}</td>
                            <td data-area="${tmp}">${tmp}</td>
                            <td class='price'><input type="number"  class="price layui-input" min="0" value="${lists[i].price}"/></td>
                            <td class='totalPrice'>${numberFormat(tmp * lists[i].price,'currency')}</td>
                            </tr>`
                }
                html += `</tbody></table>`
                layer.open({
                    type: 1,
                    title: "编辑",
                    area: ['70%', '90%'],
                    content: html,
                    btn: ['确认', '取消'],
                    skin: 'my-skin',
                    success:function(){
                        $('table.budget tbody td.price input').on('input propertychange',function(){
                            var input = $(this).val();
                            var totalPrice = Number($(this).parent().prev().data('area'))*Number(input);
                            $(this).parent().next().empty().html(numberFormat(totalPrice,'currency'))
                        });
                    },
                    yes: function (index, layero) {
                        var tr = $('table.budget tbody tr');
                        var save = [];
                        var professionId;
                        var price;
                        var budgetId;
                        for (var i = 0; i < tr.length; i++) {
                            budgetId = $(tr[i]).find('td.professionId').data('id');
                            professionId = $(tr[i]).find('td.professionId').data('professionid');
                            price = $(tr[i]).find('td.price input').val();
                            area = $(tr[i]).find('td:nth-child(3)').data('area');
                            totalPrice = Number(price)* Number(area);
                            if (price !== '') {
                                save.push({id: (budgetId==null)?null:Number(budgetId), professionId: professionId, price: price,totalPrice:totalPrice})
                            }
                        }
                        $.ajax({
                            url: url + "/project/project/editBudget",
                            type: "POST",
                            async: false,
                            data: {
                                sectionId: id,
                                areaId: areaId,
                                projectId: projectId,
                                data:save,
                                token: getToken()
                            },
                            success: function (r) {
                                if (r.code == 100000) {
                                    tips('编辑预算',r);
                                    setTimeout(function () {
                                        layer.closeAll();
                                        table.reload('lists');
                                    }, 2000)
                                } else {
                                    tips('编辑预算',r);
                                }
                            }
                        })
                    }
                })
            } else if(data.event == 'budgetAndCost'){
                // var id=data.data.id;
                // var lists = '';
                // $.ajax({
                //     url:url+'/project/project/budgetAndCost',
                //     type: "POST",
                //     async: false,
                //     data: {
                //         sectionId:id,
                //         token:getToken()
                //     },
                //     success:function(r){
                //         if(r.code!=100000){
                //             tips('成本',r);
                //             return false;
                //         }else{
                //             lists = r.data;
                //         }
                //     }
                // });
                // html = `<table class="layui-table budget" style="width:98%;margin-left:auto;margin-right:auto;"><thead><tr><th>编号</th><th>工种</th><th>面积（平方米）</th><th>预算单价（元/平方米）</th><th>预算总价（元）</th><th>成本单价（元/平方米）</th><th>成本总价（元）</th></tr></thead><tbody>`
                // for (var i= 0;i<lists.length;i++){
                //     var tmp = 0;
                //     if (lists[i].isFormwork === 0){
                //         tmp = lists[i].area;
                //     }else{
                //         tmp = lists[i].formworkArea;
                //     }
                //     html+=`<tr>
                //             <td>${i+1}</td>
                //             <td>${lists[i].name}</td>
                //             <td>${tmp?tmp:'-'}</td>
                //             <td>${lists[i].budgetPrice==null?'-':lists[i].budgetPrice}</td>
                //             <td>${(tmp>0 && lists[i].budgetPrice!=null)?(tmp * lists[i].budgetPrice):'-'}</td>
                //             <td>${(tmp>0 && lists[i].totalPrice!=null)?(lists[i].totalPrice/tmp).toFixed(2):'-'}</td>
                //             <td>${lists[i].totalPrice==null?'-':lists[i].totalPrice}</td>
                //             </tr>`
                // }
                // html += `</tbody></table>`
                // layer.open({
                //     type: 1,
                //     title: "预算与成本",
                //     area: ['70%', '90%'],
                //     content: html,
                //     btn: ['关闭'],
                //     skin: 'my-skin',
                // })
            } else if (data.event == 'formworkArea') {
                let sectionId = data.data.id;
                layer.open({
                    type: 1,
                    title: "设置模板面积",
                    area: ['40%', '50%'],
                    content: `
                    <form class='layui-form layerOpen'>
                        <div class='layui-item'>
                            <div class='layui-inline'>
                                <label class='layui-form-label'>模板面积</label>
                                <div class='layui-input-block'>
                                    <input type='number'  class='layui-input'id='budgetFormworkArea' min="0" value="${Number(data.data.budgetFormworkArea)}">
                                </div>
                            </div>
                        </div>
                    </form>
                `,
                    btn: ['确认', '取消'],
                    skin: 'my-skin',
                    yes: function (index, layero) {
                        var budgetFormworkArea = Number($('#budgetFormworkArea').val());
                        $.ajax({
                            url: url + "/project/project/setBudgetFormworkArea",
                            type: "POST",
                            async: false,
                            data: {
                                id: sectionId,
                                budgetFormworkArea: budgetFormworkArea,
                                token: getToken()
                            },
                            success: function (r) {
                                if (r.code == 100000) {
                                    tips('设置模板面积', r);
                                    setTimeout(function () {
                                        layer.closeAll();
                                        table.reload('lists');
                                    }, 2000)
                                } else {
                                    tips('设置模板面积', r);
                                }
                            }
                        })
                    }
                })
            }
        })

        //搜索
        $('body').on('click', '#search', function () {
            var search = $(this).parent().prev().find('input').val();
            table.reload('lists', {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    token: getToken(),
                    search: search
                }
            })
        })
    });

</script>

</html>